package com.ysq.www.common.utils.message;


import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

public class HttpClientUtils {

    //获取openid
    public static JSONObject getWxUserOpenid(String code, String APPID, String APPSecret) throws IOException {
        //拼接url
        StringBuilder url = new StringBuilder("https://api.weixin.qq.com/sns/jscode2session?");
        url.append("appid=");//appid设置
        url.append(APPID);
        url.append("&secret=");//secret设置
        url.append(APPSecret);
        url.append("&js_code=");//code设置
        url.append(code);
        url.append("&grant_type=authorization_code");
        //Map<String, Object> map = null;
        JSONObject res = null;
        HttpClient client = HttpClientBuilder.create().build();//构建一个Client
        HttpGet get = new HttpGet(url.toString());    //构建一个GET请求
        HttpResponse response = client.execute(get);//提交GET请求
        HttpEntity result = response.getEntity();//拿到返回的HttpResponse的"实体"
        String content = EntityUtils.toString(result);
        System.out.println(content);//打印返回的信息
        res = JSONObject.parseObject(content);
        //JSONObject res = JSONObject.fromObject(content);//把信息封装为json
        //把信息封装到map
        //map = MdzwUtils.parseJSON2Map(res);//这个小工具的代码在下面
        return res;
    }

    //获取小程序全局接口调用凭证
    public static JSONObject getAccessToken(String appId, String APPSecret ) throws IOException {
        //拼接地址
        StringBuffer sbUrl = new StringBuffer("https://api.weixin.qq.com/cgi-bin/token?");
        sbUrl.append("grant_type=client_credential")
                .append("&appid=")
                .append(appId)
                .append("&secret=")
                .append(APPSecret);
        HttpClient client = HttpClientBuilder.create().build();//构建一个Client
        HttpGet get = new HttpGet(sbUrl.toString());//构建一个GET请求
        HttpResponse response = client.execute(get);//提交GET请求
        HttpEntity result = response.getEntity();//拿到返回的HttpResponse的"实体"
        String r = EntityUtils.toString(result);
        System.out.println(r);//打印返回的信息
        JSONObject res = JSONObject.parseObject(r);
        return res;
    }


}
